﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

using Quester.Models;

namespace Quester.Controllers
{
    [Authorize(Roles="teacher")]
    public class TeacherController : Controller
    {
        Quester.Models.QuesterEntities ent = new QuesterEntities();

        //
        // GET: /Teacher/

        public ActionResult Index()
        {
            return RedirectToAction("TestList");    
        }

        [HttpGet]
        public ActionResult TestList()
        {
            XListViewModel model = new XListViewModel();

            model.Title = "Тести";

            model.Items = (from test in ent.Test
                           select new Item()
                           {
                               ID = test.TestID,
                               Value = test.Subject + ":" + test.TestName //String.Format("{0} - {1}  {2} зап.", test.Subject, test.TestName, test.Question.Count)
                           }).ToList();

            model.CaptionBtns.Add(new ActionBtn() { Title = "Новий тест", Action = "AddTest", Controller = "Teacher", Icon = "IconAdd.png", CssClass = "ActButton" });

            model.ItemBtns.Add(new ActionBtn() { Title = "Відкрити", Action = "OpenTest", Controller = "Teacher", Icon = "IconAdd.png", CssClass = "ActButton" });
            model.ItemBtns.Add(new ActionBtn() { Title = "Деталі", Action = "TestDetail", Controller = "Teacher", Icon = "IconDetail.png", CssClass = "ActButton" });
            model.ItemBtns.Add(new ActionBtn() { Title = "Редаг.", Action = "TestEdit", Controller = "Teacher", Icon = "IconEdit.png", CssClass = "ActButton" });
            model.ItemBtns.Add(new ActionBtn() { Title = "Видал.", Action = "DeleteTest", Controller = "Teacher", Icon = "IconDelete.png", CssClass = "ActButton" });

            ViewBag.List = model;

            return View();
        }


        [HttpGet]
        public ActionResult AddTest()
        {
            Test testModel = new Test();
            testModel.TestID = Guid.NewGuid();

            return View(testModel);
        }

        [HttpPost]
        public ActionResult AddTest(Test testModel)
        {
            if (ModelState.IsValid)
            {
                testModel.CreateDate = DateTime.Now;
                testModel.LastModDate = DateTime.Now;

                testModel.CreatorID = (Guid)Membership.GetUser().ProviderUserKey;
                testModel.EditorID = testModel.CreatorID;

                ent.Test.AddObject(testModel);
                ent.SaveChanges();

                return RedirectToAction("TestDetail", new {@ID = testModel.TestID});
            }

            return RedirectToAction("AddTest");
        }

        [HttpGet]
        public ActionResult TestDetail(Guid ID)
        {
            Test test = ent.Test.First(rec => rec.TestID == ID);

            TestVModel model = new TestVModel()
            {
                TestID = ID,
                CreationDate = test.CreateDate,
                LastModDate = test.LastModDate,
                CreatorID = test.CreatorID,
                EditorID = test.EditorID,
                CreatorName = test.Teacher.LastName + test.Teacher.Name[0],                   //Link for Creator Teacher entity. Checked in  DB.Deisgner
                EditorName = test.Teacher1.LastName + test.Teacher1.Name[0],                  //Link for Editor Teacher entity. Checked in  DB.Deisgner
                Subject = test.Subject,
                TestName = test.TestName,
                Questions = (from rec in test.Question
                             select new QuestionVModel()
                             {
                                 QuestionID = rec.QuestionID,
                                 QuestionStr = rec.Question1,
                                 Answers =
                                 (from answ in rec.Ansver
                                  select new AnswerVModel()
                                  {
                                      AnswerID = answ.AnsverID,
                                      Answer = answ.AnsverText,
                                      IsRight = (answ.IsRight ?? false)
                                  }).ToList()
                             }).ToList()
            };


            return View(model);
        }

        [HttpGet]
        public ActionResult TestEdit(Guid ID)
        {
            Test t = ent.Test.First(rec => rec.TestID == ID);

            TestVModel tvm = new TestVModel() 
            {
                CreationDate = t.CreateDate,
                CreatorID = t.CreatorID,
                EditorID = t.EditorID,
                LastModDate = t.LastModDate,
                Subject = t.Subject,
                TestName = t.TestName,
                TestID = t.TestID
            };



            return View(tvm);
        }

        [HttpPost]
        public ActionResult TestEdit(TestVModel test)
        {
            if (ModelState.IsValid)
            {
                Test t = ent.Test.First(rec => rec.TestID == test.TestID);
                t.TestName = test.TestName;
                t.Subject = test.Subject;
                t.LastModDate = DateTime.Now;
                t.EditorID = (Guid)Membership.GetUser().ProviderUserKey;
                ent.SaveChanges();
                return RedirectToAction("TestList");
            }
            return RedirectToAction("TestEdit", new { @ID = test.TestID });
        }

        [HttpGet]
        public ActionResult DeleteTest(Guid ID)
        {
            Test t = ent.Test.First(rec => rec.TestID == ID);
            TestDeleteVModel tDelete = new TestDeleteVModel() 
            {
                ID = t.TestID,
                Subject = t.Subject,
                TestName = t.TestName
            };
            return View(tDelete);
        }

        [HttpPost]
        public ActionResult DeleteTest(TestDeleteVModel tDelete)
        {
            var qToDelete = from q in ent.Question
                            where q.TestID == tDelete.ID
                            select q;

            foreach(Question q in qToDelete)
            {
                ent.Question.DeleteObject(q);
            }


            ent.Test.DeleteObject(ent.Test.First(rec => rec.TestID == tDelete.ID));
            ent.SaveChanges();

            return RedirectToAction("TestList");
        }

        public ActionResult AddQuestion(Guid ID)
        {
            QuestionVModel qModel = new QuestionVModel() { TestID = ID, QuestionID = Guid.NewGuid() };

            return View(qModel);
        }

        [HttpPost]
        public ActionResult AddQuestion(QuestionVModel model)
        {
            if (ModelState.IsValid)
            {
                Question q = new Question()
                {
                    Question1 = model.QuestionStr,
                    Illustration = null,
                    TestID = model.TestID,
                    QuestionID = Guid.NewGuid()
                };

                ent.Question.AddObject(q);
                ent.SaveChanges();

                foreach(AnswerVModel ans in model.Answers)
                {
                    if (ans.Answer != null && ans.Answer != String.Empty)
                    {
                        ent.Ansver.AddObject(new Ansver()
                                          {
                                              AnsverID = Guid.NewGuid(),
                                              AnsverText = ans.Answer,
                                              IsRight = ans.IsRight,
                                              QuestionID = q.QuestionID,
                                          });
                    }
                }

                ent.SaveChanges();

            }


            return RedirectToAction("TestDetail", new { @ID = model.TestID});
        }

        [HttpGet]
        public ActionResult QuestionEdit(Guid ID)
        {
            

            Question q = (from qItem in ent.Question
                         where qItem.QuestionID == ID
                         select qItem).First();

            QuestionVModel qvm = new QuestionVModel() 
            {
                QuestionID = ID,
                QuestionStr = q.Question1,
                TestID = q.TestID
            };

            List<Ansver> answrs = (from qItem in q.Ansver
                                   orderby qItem.IsRight, qItem.AnsverText descending
                                   select qItem).Reverse().ToList(); 

            for (int i = 0; i < q.Ansver.Count; i++ )
            {
                qvm.Answers[i].Answer = answrs[i].AnsverText;
                qvm.Answers[i].AnswerID = answrs[i].AnsverID;
                qvm.Answers[i].IsRight = answrs[i].IsRight ?? false;
            }

            return View(qvm);
        }

        [HttpPost]
        public ActionResult QuestionEdit(QuestionVModel model)
        {
            if (ModelState.IsValid)
            {
                Question q = ent.Question.First(qItem => qItem.QuestionID == model.QuestionID);

                List<Guid> ansIDs = (from ansItem in q.Ansver
                                    select ansItem.AnsverID).ToList();

                foreach (Guid id in ansIDs)
                {
                    ent.Ansver.DeleteObject(ent.Ansver.First(item => item.AnsverID == id));
                }

                ent.SaveChanges();

                q = ent.Question.First(qItem => qItem.QuestionID == model.QuestionID);

                q.Question1 = model.QuestionStr;
                q.Illustration = null;

                foreach (AnswerVModel ans in model.Answers)
                {
                    if (ans.Answer != null && ans.Answer != String.Empty)
                    {
                        q.Ansver.Add(new Ansver()
                        {
                            AnsverID = Guid.NewGuid(),
                            AnsverText = ans.Answer,
                            IsRight = ans.IsRight,
                            QuestionID = q.QuestionID
                        });
                    }
                }

                //foreach (AnswerVModel ans in model.Answers)
                //{
                //    if (ans.Answer != null && ans.Answer != String.Empty)
                //    {
                //        ent.Ansver.AddObject(new Ansver()
                //        {
                //            AnsverID = Guid.NewGuid(),
                //            AnsverText = ans.Answer,
                //            IsRight = ans.IsRight,
                //            QuestionID = q.QuestionID,
                //        });
                //    }
                //}

                ent.SaveChanges();

            }


            return RedirectToAction("TestDetail", new { @ID = model.TestID });
        }

        [HttpGet]
        public ActionResult QuestionDelete(Guid ID)
        {
            Question delQuest = ent.Question.First(q => q.QuestionID == ID);



            return View(delQuest);
        }

        [HttpPost]
        public ActionResult QuestionDelete(Question model)
        {

            if (ModelState.IsValid)
            {
                Question q = ent.Question.First(qItem => qItem.QuestionID == model.QuestionID);

                List<Guid> ansIDs = (from ansItem in q.Ansver
                                     select ansItem.AnsverID).ToList();

                foreach (Guid id in ansIDs)
                {
                    ent.Ansver.DeleteObject(ent.Ansver.First(item => item.AnsverID == id));
                }

                ent.Question.DeleteObject(q);

                ent.SaveChanges();
            }

            return RedirectToAction("TestDetail", new { @ID = model.TestID });
        }

        [HttpGet]
        public ActionResult OpenTest(Guid ID)
        {
            DateTime Now = DateTime.Now;
            List<SelectListItem> Days = new List<SelectListItem>();
            for (int i = 1; i < DateTime.DaysInMonth(Now.Year, Now.Month) + 1; i++)
            {
                Days.Add(new SelectListItem() { Text = i.ToString(), Value = i.ToString() });
            }

            Days[Now.Day - 1].Selected = true;

            ViewBag.SecectDayList = Days;
            TestOpenVModel model = new TestOpenVModel() 
            {
                OpenAt = DateTime.Now,
                ClodeAt = DateTime.Now.AddHours(1.5),
                OpenTestID = ID,
                GoupID = ent.Group.First().GroupID
            };

             List<SelectListItem> groups = (from grp in ent.Group
                                 orderby grp.Kafedra
                                 select grp).AsEnumerable().Select(x => new SelectListItem()
                                    {
                                         Text = x.Kafedra + " - " + x.GroupName,
                                         Value = x.GroupID.ToString()
                                     }).ToList();
            groups[0].Selected = true;

            ViewBag.GroupList = groups;
            return View(model);
        }

        [HttpPost]
        public ActionResult OpenTest(TestOpenVModel model)
        {
            foreach (Student st in ent.Group.First(gr => gr.GroupID == model.GoupID).Student)
            {

                ent.OpenTest.AddObject(new OpenTest()
                {
                    CloseDate = model.ClodeAt,
                    OpenDate = model.OpenAt,
                    OpenerID = (Guid)Membership.GetUser().ProviderUserKey,
                    StudentID = st.StudentID,
                    TestID = model.TestID
                });
            }

            ent.SaveChanges();

            return RedirectToAction("TestList");
        }


        [HttpGet]
        public ActionResult OpenTestList()
        {
            //List<TestOpenVModel> testList = from ot in ent.OpenTest
            //                                select new TestOpenVModel()
            //                                {
            //                                    ClodeAt = ot.CloseDate,
            //                                    GoupID = ot.s
            //                                }

            return View();
        }


    }
}
